﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Collections;

namespace SmartPhoneClient
{
    public partial class Form1 : Form
    {
        Socket clientSocket;
        public Thread receive;
        IPEndPoint p;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            objShowForm2 = new DelegateShowForm2(ShowForm2);
            objShowForm4 = new DelegateShowForm4(ShowForm4);
        }

        //----用于显示Form2的代理----
        delegate void DelegateShowForm2();

        DelegateShowForm2 objShowForm2;

        private void ShowForm2()
        {
            MessageBox.Show("登录成功！");
            Form2 f2 = new Form2();
            f2.Show();
        }
        //---------------------------

        //----用于显示Form4的代理----
        delegate void DelegateShowForm4();

        DelegateShowForm4 objShowForm4;

        private void ShowForm4()
        {
            Form4 f4 = new Form4();
            f4.Show();
        }
        //---------------------------
        


        private void menuItem1_Click(object sender, EventArgs e)
        {
            string serveraddress = textBox3.Text;
            int serverport = 4567;
            p = new IPEndPoint(IPAddress.Parse(serveraddress), serverport);
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(p);
            if (clientSocket.Connected)
            {
                label4.Text = "已经成功连接到服务器";
                Infomation.MySocket = clientSocket; //将连接好的Socket进行静态保存

                string userName = textBox1.Text;
                string userPassword = MD5Convert(textBox2.Text);
                string command = "WaiterLogin|" + userName + "|" + userPassword;
                Byte[] outbytes = System.Text.Encoding.Unicode.GetBytes(command.ToCharArray());
                clientSocket.Send(outbytes, outbytes.Length, 0);

                receive = new Thread(new ThreadStart(Receive));
                receive.Start();
            }
        }

        private string MD5Convert(string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = System.Text.Encoding.Default.GetBytes(str);
            byte[] result = md5.ComputeHash(data);
            string ret = "";
            for (int i = 0; i < result.Length; i++)
                ret += result[i].ToString("x").PadLeft(2, '0');
            return ret;
        }

        /// <summary>
        /// 处理各种消息
        /// </summary>
        private void Receive()
        {
            //try
            //{
                while (true)
                {
                    Byte[] buffer = new Byte[10240]; //定义字节buffer变量
                    int bufLen = 0;
                    bufLen = clientSocket.Available;  //接收数据量
                    clientSocket.Receive(buffer, 0, bufLen, SocketFlags.None);  //数据存入buffer中
                    if (bufLen != 0)
                    {
                        string serverresponse = System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length).Substring(0, bufLen);//转换为字符串（截取有用字符部分）
                        string[] s = serverresponse.Split(new Char[] { '|' });
                        string type = s[0];

                        if (type == "Login Successful")
                        {
                            this.Invoke(objShowForm2); 
                        }
                        //else if (serverresponse.Equals("Login Failed"))
                        else if (type == "Login Failed")
                        {
                            MessageBox.Show("登录失败！");
                        }
                        else if (type == "CheckFoodBack")
                        {
                            string tableID = s[1];
                            string foodID = s[2];
                            string foodName = s[3];
                            string price = s[4];
                            string foodState = s[5];
                            string intro = s[6];
                            string discount = s[7];
                            string cookID = s[8];
                            string custNotes = s[9];

                            if (Int32.Parse(foodState) == 1)
                            {
                                string info = "桌号：" + tableID + "\r\n菜号：" + foodID + "\r\n菜名：" + foodName + "\r\n价格：" + price + "\r\n当前状态：配料齐全可做\r\n介绍：" + intro + "\r\n折扣：" + discount + "\r\n厨师号：" + cookID;
                                MessageBox.Show(info);
                                Infomation.Order.Add("AddOrderItem|" + tableID + "|" + foodID + "|" + cookID + "|" + custNotes);
                            }
                            else if (Int32.Parse(foodState) == 0)
                            {
                                string info = "菜号：" + foodID + "\r\n菜名：" + foodName + "\r\n当前配料无货，不可做";
                                MessageBox.Show(info);
                            }
                        }
                        else if (type == "AddOrderItemFailed")
                        {
                            string tableID = s[1];
                            string foodID = s[2];
                            string cookID = s[3];
                            string custNotes = s[4];
                            string info = "订单提交错误：\r\n桌号：" + tableID + "\r\n菜号：" + foodID + "\r\n厨师号：" + cookID + "\r\n备注：" + custNotes;
                            MessageBox.Show(info);
                        }
                        else if (type == "CheckOrderBack")
                        {
                            byte[] orderByte = System.Text.Encoding.Unicode.GetBytes(s[1]);

                            CompactFormatter.CompactFormatter ser = new CompactFormatter.CompactFormatter();
                            MemoryStream stream = new MemoryStream(orderByte);   //theBytes是序列化后的结果
                            RMSClass.OrderItem[] order = (RMSClass.OrderItem[])ser.Deserialize(stream);
                            stream.Close();

                            Infomation.CheckedOrder = order;    //Infomation.CheckedOrder用于Form4_Load对查询结果进行加载
                            
                            this.Invoke(objShowForm4); 
                        }
                    }
                }
            //}
            //catch (Exception exp)
            //{
            //    MessageBox.Show(exp.ToString());
            //}   
        }
    }
}